package com.abel.bigwater.data.kente

import com.abel.bigwater.data.NotEnoughDataException
import com.abel.bigwater.data.UnknownPacketException
import io.netty.buffer.ByteBuf

/**
 * 57 41 49 54 43 4f 4d 4d 2c 47 50 52 53 49 44 3d 32 30 31 30 36 31 31 30 2c
 * WAITCOMM,GPRSID=20106110,
 */
class KenteWaitComm : KentePacket() {
    companion object {
        const val head = "WAITCOMM,GPRSID="

        const val dataLen = 8

        /**
         * single:
         * 7e cb 32 01 68 14 34 01 f4 9a 01 00 00 00 00 00 00 00 00 00 00 00 00
        00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
        00 00 00 00 00 00 00 3f 01
         */
        fun parse(buf: ByteBuf): List<KenteWaitComm>? {
            if (buf.readableBytes() < KentePacket.head.length) return null

            val head2 = ByteArray(head.length).apply { buf.duplicate().readBytes(this) }
            if (!head2.contentEquals(head.toByteArray())) {
                // continue to parse
                throw UnknownPacketException("不支持的消息: ${head2.toString(Charsets.UTF_8)}")
            }

            if (buf.readableBytes() < head.length + 1 + dataLen) {
                throw NotEnoughDataException("字节数不足一帧: ${buf.readableBytes()}")
            }

            val dlist = ArrayList<KenteWaitComm>()

            val buf1 = buf.readBytes(head.length + 1 + dataLen)
            val msg = buf1.toString(Charsets.ISO_8859_1)
            buf1.skipBytes(head.length)
            try {
                buf1.readBytes(dataLen).also {
                    dlist.add(KenteWaitComm().apply {
                        command = head
                        backArray = ByteArray(dataLen).apply { it.duplicate().readBytes(this) }
                        rtuId = it.toString(Charsets.ISO_8859_1).toLong()
                    })
                }
            } catch (ex: NumberFormatException) {
                throw UnknownPacketException("invalid rtu-id: ${msg}")
            }

            return dlist
        }
    }
}